package com.woniuxy.creditsystem.mortgagemag.controller;

import com.woniuxy.creditsystem.common.bean.ResultMsg;
import com.woniuxy.creditsystem.common.bean.VehicleInfo;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;


@RequestMapping("/vehiclePOI")
@RestController
public class VehiclePOIController {


        //导出之先将页面table解析为excel并保存到本地服务器
        @RequestMapping(value = "getVehicel",produces = {"application/json;charset=utf-8"})
        public ResultMsg getExcel(@RequestBody ArrayList<VehicleInfo> list) throws IOException {
            System.out.println(list);
            ResultMsg msg = new ResultMsg();
            msg.setCode(200);
            //设置表对象
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建时间戳作为表名
            Date date = new Date();
            long time = date.getTime();
            String tableName = time+"";
            //创建表页面
            HSSFSheet sheet = workbook.createSheet("tableinfo");
            //创建字段行
            HSSFRow row = sheet.createRow(0);
            //给字段行添加字段
            HSSFCell cell1 = row.createCell(0);
            cell1.setCellValue("序号");
            HSSFCell cell2 = row.createCell(1);
            cell2.setCellValue("车标");
            HSSFCell cell3 = row.createCell(2);
            cell3.setCellValue("车辆牌号");
            HSSFCell cell4 = row.createCell(3);
            cell4.setCellValue("车身颜色");
            HSSFCell cell5 = row.createCell(4);
            cell5.setCellValue("客户姓名");
            HSSFCell cell6 = row.createCell(5);
            cell6.setCellValue("客户手机号");

            //用Excel表对象创建CellStyle对象
            CellStyle cellStyle = workbook.createCellStyle();
            //用Excel表对象获取CreationHelper对象
            CreationHelper createHelper = workbook.getCreationHelper();
            //给cellStyle对象设置Date格式
            cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
            for (int i = 1; i <list.size()+1 ; i++) {
                //创建每一行
                HSSFRow rowy = sheet.createRow(i);
                //给每一行添加数据
                HSSFCell celly1 = rowy.createCell(0);
                celly1.setCellValue(i);

                HSSFCell celly2 = rowy.createCell(1);
                celly2.setCellValue(list.get(i-1).getBrands());

                HSSFCell celly3 = rowy.createCell(2);
                celly3.setCellValue(list.get(i-1).getVehicleLicense());

                HSSFCell celly4 = rowy.createCell(3);
                celly4.setCellValue(list.get(i-1).getCarColor());

                HSSFCell celly5 = rowy.createCell(4);

                celly5.setCellStyle(cellStyle);
                celly5.setCellValue(list.get(i-1).getCustomerInfo().getName());

                HSSFCell celly6 = rowy.createCell(5);
                celly6.setCellValue(list.get(i-1).getCustomerInfo().getTelephone());

            }
            //创建文件夹
            String dir="D://POI";
            File file = new File(dir);
            if (!file.exists()){
                file.mkdir();
            }

            FileOutputStream os = new FileOutputStream("D://POI/"+tableName+".xls");
            workbook.write(os);
            os.flush();
            os.close();
            msg.setMsg("D://POI/"+tableName+".xls");
            return msg;
        }

        /**
         *
         * @param path  文件在服务器的路径，由a标签携带
         * @param userAgent  用来判断是否是ie浏览器的一个响应头
         * @return 设置响应头额实体对象
         */
        //导出之再根据文件名将文件以流的形式返回给a标签
        @RequestMapping("/download")
        public ResponseEntity<byte[]> download(String path, @RequestHeader("User-Agent") String userAgent){
            System.out.println(path);
            //判断当前路径是否有文件
            File file = new File(path);
            if(!file.exists()){
                return null;
            }
            //构建状态码200
            ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
            //设置文件长度
            builder.contentLength(file.length());
            //告诉前端，相应数据位二进制流
            builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
            try {
                String fileName = URLEncoder.encode("table.xls","UTF-8");
                if(userAgent.indexOf("MSIE")>0){
                    builder.header("Content-Disposition","attachment;filename="+fileName);
                }else {
                    builder.header("Content-Disposition","attacher;filename*=UTF-8''"+fileName);
                }
                //通过fileutil工具类将文件读取到相应实体中
                return builder.body(FileUtils.readFileToByteArray(file));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //文件响应回去后就将服务器的文件删除掉，避免内存的溢出
                file.delete();
                System.out.println("文件已删除");
            }
            return null;
        }



    }
